package me.seawenc.db.migration.helper;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;

/**
 * 文件操作工具类
 */
public class FileHelper {

    /**
     * sonar提示不允许只含有静态属性的类有公共方法，因此添加一个静态方法
     */
    private FileHelper() {}

    /**
     * 读取resources 目录下的文件
     *
     * @param path resources下的路径
     * @return String
     */
    public static String readResFile(String path) {
        InputStream in = FileHelper.class.getResourceAsStream(path);
        assertFileExist(in,path);
        try {
            InputStreamReader r = new InputStreamReader(in, "UTF-8");
            String result = new BufferedReader(r).lines().collect(Collectors.joining(System.lineSeparator()));
            r.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 一行一条数据,jsons格式
     * @param path
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> readResJsonsFile(String path, Class<T> clazz) throws Exception {
        InputStream in = FileHelper.class.getResourceAsStream(path);
        if(path.endsWith(".gz")) {
            in = new GZIPInputStream(in);
        }
        List<T> lines = readStreamToList(clazz, in);
        in.close();
        return lines;
    }
    public static List<String> readResJsonsFile(String path) throws Exception {
        return readResJsonsFile(path,String.class);
    }

    /**
     * 读取配置文件下的文件内容,必须是json格式
     * @param path  path
     * @param clazz clazz
     * @return T
     * @Description: 目录下的文件
     * @author: xyh
     * @Date: 2020年05月11日 15:08
     **/
    public static <T> T readResFile(String path, Class<T> clazz) {
        String ctn = readResFile(path);
        return JSONObject.parseObject(ctn, clazz);
    }

    /**
     * 读取项目外部的文件,一行一条记录
     * @param path
     * @return
     * @throws Exception
     */
    public static List<String> readExtFile(String path) throws Exception {
        InputStream inputStream=new FileInputStream(path);
        assertFileExist(inputStream);
        if(path.endsWith(".gz")) {
            inputStream = new GZIPInputStream(inputStream);
        }
        List<String> strings = readStreamToList(String.class, inputStream);
        inputStream.close();
        return strings;
    }

    public static Properties readExtResFile(String path) throws Exception {
        // 过滤掉注释行
        List<String> strings = readExtFile(path).stream().map(line-> line.trim())
                .filter(line->!line.startsWith("#")).collect(Collectors.toList());
        Properties props=new Properties();
        for (String line:strings){
            int index = line.indexOf("=");
            props.setProperty(line.substring(0,index).trim(),line.substring(index+1).trim());
        }
        return props;
    }

    public static <T> List<T> readStreamToList(Class<T> clazz, InputStream in) throws IOException {
        assertFileExist(in);
        InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
        BufferedReader reader = new BufferedReader(inReader);
        List<String> lines=new ArrayList<>();
        String line;
        while(reader.ready()&&(line = reader.readLine()) != null){
            lines.add(line);
        }
        //如果是格式化过后的文件，则合并成一条数据
//        if(lines.get(0).equals("{")){
//        if("{".equals(lines.get(0))){
//            line=String.join("",lines.toArray(new String[]{}));
//            lines.clear();
//            lines.add(line);
//        }
        //将对旬格式转换成指定对象
        List<T> ret=new ArrayList<>();
        for(String s:lines){
            if(clazz.getSimpleName().equals(String.class.getSimpleName())){
                ret.add((T)s);
                continue;
            }
            ret.add(JSONObject.parseObject(s, clazz));
        }
        reader.close();
        inReader.close();
        in.close();
        return ret;
    }

    public static boolean resFileExist(String path){
        return FileHelper.class.getResourceAsStream(path)!=null;
    }

    private static void assertFileExist(InputStream in,String... path) {
        if(in ==null){
            path= Optionalx.ofByDefGet(path,new String[]{""});
            throw new IllegalArgumentException("传入的文件不存在,path:"+path[0]);
        }
    }

    public static void writeToExtFile(String path,String ctn) throws IOException {
        File file = new File(path);
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        if(!file.exists()){
            file.createNewFile();
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
            writer.write(ctn);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
